//
//  HKWebViewController.m
//  YNDemo
//
//  Created by 胡锦涛 on 2020/11/11.
//

#import "HKWebViewController.h"
#import "HKWebViewController+JSBridge.h"
#import <HKLibBase/HKLibBaseHeader.h>
#import <HKLibCommon/HKPrefixHeader.h>
// 架构模式
#import "BifrostHeader.h"
#import "WebViewLibService.h"
#import "LibWebViewBundle.h"
@interface HKWebViewController ()<WKNavigationDelegate,UIImagePickerControllerDelegate>

@end

@implementation HKWebViewController
{
    NSTimer * timer ;
    void(^hanlder)(id value,BOOL isComplete);
    int value;
}
+ (void)load {
    [Bifrost bindURL:kRouteWebViewPage
           toHandler:^id _Nullable(NSDictionary * _Nullable parameters) {
        return [HKWebViewController new];
    }];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.delegate = self;
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColorWhite;
    self.webView=[[HKWebView alloc] initWithFrame:CGRectMake(0, 0, HK_DEVICE_WIDTH, HK_DEVICE_HEIGHT-HK_NO_NAV_HEIGHT-HK_NAVBAR_HEIGHT)];
    [self.view addSubview:self.webView];
    HK_AdjustsContentInsets(self.webView.scrollView);
    [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    [self.webView setDebugMode:true];
    [self.webView customJavascriptDialogLabelTitles:@{@"alertTitle":@"Notification",@"alertBtn":@"OK"}];
    self.webView.navigationDelegate=self;
    [self registerNativeMethod];
    [self addNoti];
    if (self.webUrl) {
        NSURLRequest * request = [NSURLRequest requestWithURL:_webUrl];
        [self.webView loadRequest:request];
    }
}
- (void)registerNativeMethod
{
    // 注册Native代码
    [self.webView callHandler:@"startTimer" completionHandler:^(NSNumber * _Nullable value) {
        NSLog(@"Timer: %@",value);
    }];
    
    // set javascript close listener
    [self.webView setJavascriptCloseWindowListener:^{
        NSLog(@"window.close called");
    } ];
    [self.webView addJavascriptObject:self namespace:nil];
}
- (void)addNoti
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(scanSucceed:) name:@"scanSucceed" object:nil];
}
#pragma mark - KVO

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void *)context
{
    if (object == self.webView) {
        
        if ([keyPath isEqualToString:@"title"]) {
            if (self.webTitle && [self.webTitle qmui_trim].length > 0) {
                self.title = self.webTitle;
            }else {
                self.title = change[@"new"];
            }
        }
    }
    
}
- (void)setWebUrl:(NSURL *)webUrl {
    _webUrl = webUrl;
}
-(void)dealloc {
    [self.webView removeObserver:self forKeyPath:@"title" context:nil];
}

- (void)scanSucceed:(NSNotification*)noti {
    NSLog(@"扫描成功了：您的扫描结果为>>>>>%@",noti.object);
    [self.webView callHandler:@"showScanResult" arguments:@[noti.object].mutableCopy completionHandler:^(id  _Nullable value) {
        NSLog(@"showScanResult: %@",value);
    }];
}
- (void)loadFile {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *array1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *matPath1 = [[array1 objectAtIndex:0] stringByAppendingPathComponent:@"YunNiao"];;
    //      if (![fileManager fileExistsAtPath:matPath1]) {
    NSString *matString = [[LibWebViewBundle bundle] pathForResource:@"YunNiao" ofType:@"bundle"];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [fileManager removeItemAtPath:matPath1 error:nil];
        [fileManager copyItemAtPath:matString toPath:matPath1 error:nil];
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"创建完了");
            [self ios9Load];
        });
    });
    //      }
    //      else{
    //          [self ios9Load];
    //      }
}
- (void)ios9Load {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSString *basePath = [NSString stringWithFormat:@"%@/%@",path,@"YunNiao/"];
    NSString *htmlPath = [NSString stringWithFormat:@"%@/%@",path,@"YunNiao/index.html"];
    NSURL *fileURL = [NSURL fileURLWithPath:htmlPath];
    if (@available(iOS 9.0, *)) {
        [self.webView loadFileURL:fileURL allowingReadAccessToURL:[NSURL fileURLWithPath:basePath isDirectory:YES]];
    }
}

- (void) callProgress:(NSDictionary *) args :(JSCallback)completionHandler
{
    value=10;
    hanlder=completionHandler;
    timer =  [NSTimer scheduledTimerWithTimeInterval:1.0
                                              target:self
                                            selector:@selector(onTimer:)
                                            userInfo:nil
                                             repeats:YES];
}

-(void)onTimer:t{
    if(value!=-1){
        hanlder([NSNumber numberWithInt:value--],NO);
    }else{
        hanlder(0,YES);
        [timer invalidate];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
